﻿using System;
using System.Collections.Generic;
using System.Text;

namespace FileMover.Service.Filters
{
    public class MatchExtensionFilterFactory : FilterFactoryBase<MatchExtensionFilter>
    {
        protected override string XmlLocalName
        {
            get { return "MatchExtension"; }
        }
        protected override string XmlNameSpace
        {
            get { return Model.mgr.LookupNamespace("FileMover"); }
        }
        public override string ToString()
        {
            return "Match Extension"; ///TODO: Localize
        }

    }

    public class MatchExtensionFilter : RuleItemBase, IFilter
    {
        public string Extension { get; set; }
        public UsageEnum Outcome { get; set; }

        public override void FromXml(System.Xml.XmlElement elem)
        {
            base.FromXml(elem);

            Extension = elem.GetAttribute("extension");

            var outcome = elem.GetAttribute("outcome");
            if (string.IsNullOrEmpty(outcome))
            {
                Outcome = UsageEnum.Include;
            }
            else if (string.Equals(outcome, "include"))
            {
                Outcome = UsageEnum.Include;
            }
            else if (string.Equals(outcome, "exclude"))
            {
                Outcome = UsageEnum.Exclude;
            }
            else
            {
                throw new System.Xml.XmlException(string.Format("MatchExtesion has invalid attribute value for field 'outcome': '{0}'", outcome));
            }
        }

        public override string DisplayString()
        {
            return string.Format("Filter: include all {0}-files", Extension);
        }

        #region IFilter Member

        public void Filter(ILog log, IItem item)
        {
            var itemExtension = item.GetProperty("Extension");
            if (string.IsNullOrEmpty(itemExtension))
                return;
            itemExtension = itemExtension.Trim('.');
            bool matches = string.Equals(itemExtension, Extension, StringComparison.InvariantCultureIgnoreCase);
            if (!matches)
                return;

            item.Usage = Outcome;
        }

        #endregion
    }
}
